package cn.cvs.servlet.sysUser;

import cn.cvs.pojo.SysRole;
import cn.cvs.pojo.SysUser;
import cn.cvs.service.SysRoleService;
import cn.cvs.service.SysUserService;
import cn.cvs.util.Page;
import cn.cvs.util.SpringUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(name = "ListServlet", urlPatterns = "/sys/user/list")
public class ListServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doGet ( request, response );
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding ( "utf-8" );
        response.setContentType ( "textml;charset=UTF-8" );
        SysUserService sysUserService= (SysUserService) SpringUtil.getBean ( "sysUserService" );
        SysRoleService sysRoleService= (SysRoleService) SpringUtil.getBean ( "sysRoleService" );

        List<SysRole> roleList = sysRoleService.getSysRoleList ( );
        request.setAttribute ( "roleList", roleList );

        //获取页面搜索参数
        int roleId = 0;
        if (request.getParameter ( "roleId" ) != null ) {
            roleId = Integer.parseInt ( request.getParameter ( "roleId" ) );
        }
        String realName = request.getParameter ( "realName" );

        Page<SysUser> page = new Page<> ( );
        //设置每页数据
        page.setPageSize ( 5 );
        //设置总数据
        page.setTotalCount ( sysUserService.getCount ( roleId, realName ) );
        //设置当前页
        if (request.getParameter ( "pageNo" ) != null&& Integer.parseInt (  request.getParameter ( "pageNo" ) )!=0  ) {
            page.setPageNo ( Integer.parseInt ( request.getParameter ( "pageNo" ) ) );
        }
        //获取并设置集合
        List<SysUser> list = sysUserService.getUserListByRoleIdAndRealName ( roleId, realName, page.getPageSize ( ), page.getPageNo ( )<=0?1:page.getPageNo ( ) );
        page.setList ( list );
        request.setAttribute ( "page", page );
        request.setAttribute ( "realName", realName );
        request.setAttribute ( "roleId", roleId );
        System.out.println ( page );
        request.getRequestDispatcher ( "/WEB-INF/jsp/sysUser/list.jsp" ).forward ( request, response );
    }
}
